import React, { useEffect, useState, createContext, useContext } from "react";
import QRCode from "qrcode.react";
import Draggable from "react-draggable";
import { useNavigate } from "react-router-dom";
import ExportJsonExcel from "js-export-excel";

import {
  Select,
  DatePicker,
  Space,
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Button,
  Modal,
  Tooltip,
  message,
} from "antd";
// import Dragmodal from "./Dragmodal";
// import VisibleProvider from "../../store";
import moment from "moment";
import { selectDeviceInformation, updateDevice, checkTrans } from "../../serve";
import "./equipent.scss";
const { RangePicker } = DatePicker;
const { Option } = Select;

const EqContext = createContext();

const Serch = (props) => {
  let defaultLimit = parseInt((document.body.clientHeight - 250) / 52);
  const [serchData, setSerchData] = useState({
    page: 1,
    limit: defaultLimit,
  });
  const [eqDatas, setEqDatas] = useState([]);
  function disabledDate(current) {
    return current && current > moment().endOf("day");
  }

  const downloadExcel = () => {
    var option = {};
    let dataTable = [];
    eqDatas.data.forEach((item) => {
      let obj = {
        nvr_IMEI: item.nvr_IMEI,
        typeName: item.typeName,
        nvr_state: item.nvr_state == 1 ? "在线" : "离线",
        dStartTime: item.discount_start_time,
        dEndTime: item.discount_end_time,
        inPrices: item.initial_prices,
        discount: item.discount,
        pricing: (item.initial_prices * 1e3 - item.discount * 1e3) / 1e3,
        discounta:
          (
            ((item.initial_prices * 1e3 - item.discount * 1e3) /
              (item.initial_prices * 1e3)) *
            10
          ).toFixed(2) + "折",
        salesStatus:
          item.sales_status == 1
            ? "已售"
            : item.sales_status == 2
            ? "已租"
            : item.sales_status == 3
            ? "测试机"
            : "无",
        ownership: item.nvr_ownership,
      };
      dataTable.push(obj);
    });
    option.fileName = "设备列表";
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: "sheet",
        sheetFilter: [
          "nvr_IMEI",
          "typeName",
          "nvr_state",
          "dStartTime",
          "dEndTime",
          "inPrices",
          "discount",
          "pricing",
          "discounta",
          "salesStatus",
          "ownership",
        ],
        sheetHeader: [
          "设备ID",
          "设备类型",
          "设备状态",
          "优惠开始时间",
          "优惠结束时间",
          "原价(元/天)",
          "优惠(元/天)",
          "实价(元/天)",
          "折扣",
          "属性",
          "隶属",
        ],
      },
    ];

    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };

  function queryEq() {
    selectDeviceInformation(serchData).then((res) => {
      setEqDatas(res);
    });
  }
  useEffect(() => {
    queryEq(serchData);
  }, [serchData]);
  let times = null;
  let width = 180;

  return (
    <>
      <div className="select">
        设备ID：
        <Input
          placeholder="输入设备ID"
          allowClear
          onChange={(e) => {
            times && clearTimeout(times);
            times = setTimeout(() => {
              setSerchData({
                ...serchData,
                nvrImei: String(e.target.value),
                page: 1,
              });
            }, 800);
          }}
          style={{ width: width }}
        ></Input>
      </div>
      <div className="select">
        优惠时间：
        <Space direction="vertical" size={12}>
          <RangePicker
            format="YYYY-MM-DD HH:mm"
            disabledDate={disabledDate}
            showTime={
              ({ format: "HH:mm" },
              {
                defaultValue: [
                  moment("00:00:00", "HH:mm:ss"),
                  moment("23:59:59", "HH:mm:ss"),
                ],
              })
            }
            onChange={(val) => {
              val === null &&
                setSerchData({
                  ...serchData,
                  discountStartTime: "",
                  discountEndTime: "",
                  page: 1,
                });
            }}
            onOk={(val) => {
              if (val[0] !== null && val[1] !== null) {
                setSerchData({
                  ...serchData,
                  discountStartTime: moment(val[0]).format(
                    "YYYY-MM-DD HH:mm:ss"
                  ),
                  discountEndTime: moment(val[1]).format("YYYY-MM-DD HH:mm:ss"),
                  page: 1,
                });
              }
            }}
          />
        </Space>
      </div>
      <br />
      <div className="select">
        设备状态：
        <Select
          defaultValue="全部"
          style={{ width: width }}
          onChange={(val) => {
            setSerchData({
              ...serchData,
              nvrState: val,
              page: 1,
            });
          }}
        >
          <Option value="">全部</Option>
          <Option value="1">在线</Option>
          <Option value="2">离线</Option>
        </Select>
      </div>
      <div className="select">
        设备归属：
        <Input
          placeholder="输入设备归属"
          style={{ width: width }}
          allowClear
          onChange={(e) => {
            times && clearTimeout(times);
            times = setTimeout(() => {
              setSerchData({
                ...serchData,
                nvrOwnership: e.target.value,
                page: 1,
              });
            }, 800);
          }}
        ></Input>
      </div>{" "}
      <Button
        style={{ position: "absolute", right: "10%", top: "110px" }}
        size="large"
        type="primary"
        onClick={downloadExcel}
      >
        导出数据
      </Button>
      <EqContext.Provider value={{ eqDatas, serchData, setSerchData }}>
        <EditableTable />
      </EqContext.Provider>
    </>
  );
};

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

// 表格组件
const EditableTable = (props) => {
  const { eqDatas, serchData, setSerchData } = useContext(EqContext);
  const [visible, setVisible] = useState(false);

  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState("");
  const [discount_start_time, setStartTime] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  const [Qrvisible, setQrvisible] = useState(false);
  const [selectedData, setSelectedData] = useState("");

  const isEditing = (record) => record.nvr_IMEI === editingKey;

  let navigate = useNavigate();

  const editChange = (record) => {
    form.setFieldsValue({ ...record });
    // setVisible(true);
    setSelectedData(record);
    setEditingKey(record.nvr_IMEI);
  };

  const qrcode = (record) => {
    setQrvisible(true);
    setSelectedData(record);
  };
  const toRouter = (rec) => {
    navigate(`/order?nvrId=${rec}`);
  };

  function verifyPassword() {
    setLoading(true);
    let prices =
      (selectedData.initial_prices * 1e3 - selectedData.discount * 1e3) / 1e3;

    checkTrans({ userId: localStorage.getItem("userId"), password }).then((r) =>
      !r
        ? (message.error("密码错误!"), setLoading(false))
        : updateDevice({
            discount: selectedData.discount,
            discountEndTime: selectedData.discount_end_time,
            discountStartTime: selectedData.discount_start_time,
            initialPrices: selectedData.initial_prices,
            nvrImei: selectedData.nvr_IMEI,
            nvrOwnership: selectedData.nvr_ownership,
            salesStatus: selectedData.sales_status,
            purchaseDiscountedPrices: prices,
          }).then((res) => {
            if (res.result_code == 200) {
              setEditingKey("");
              setVisible(false);
              setLoading(false);
              setSerchData({ ...serchData });
              message.success("修改成功!");
            }
          })
    );

    //
  }
  function startTimeChange(val) {
    setStartTime(moment(val._d).format("YYYY-MM-DD HH:mm:ss"));
    setSelectedData({
      ...selectedData,
      discount_start_time: moment(val).format("YYYY-MM-DD HH:mm:ss"),
    });
  }
  function endTimeChange(val) {
    setSelectedData({
      ...selectedData,
      discount_end_time: moment(val).format("YYYY-MM-DD HH:mm:ss"),
    });
    // selectedData.endTime = val._i;
  }

  const cancel = () => {
    setEditingKey("");
  };
  const pageChange = (val, dd) => {
    setSerchData({
      ...serchData,
      page: val,
      limit: dd,
    });
  };

  const save = async () => {
    let prices =
      (selectedData.initial_prices * 1e3 - selectedData.discount * 1e3) / 1e3;
    prices >= 0.01
      ? setVisible(true)
      : message.error("打折后价格不能小于 0.01");
  };

  let draggleRef = React.createRef();
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const [disabled, setDisabled] = useState(true);
  const onStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      bounds: {
        left: -targetRect.left + uiData.x,
        right: clientWidth - (targetRect.right - uiData.x),
        top: -targetRect.top + uiData.y,
        bottom: clientHeight - (targetRect.bottom - uiData.y),
      },
    });
  };

  let max = 999999;
  let defaultLimit = parseInt((document.body.clientHeight - 250) / 52);

  const columns = [
    {
      title: "设备ID",
      dataIndex: "nvr_IMEI",
      fixed: "left",
      width: 85,
      ellipsis: true,
      render: (val) => (
        <Tooltip placement="top" title={val}>
          <span>{val}</span>
        </Tooltip>
      ),
      editable: false,
    },
    {
      title: "设备类型",
      dataIndex: "typeName",
      ellipsis: true,
      render: (val) => (
        <Tooltip placement="top" title={val}>
          <span>{val}</span>
        </Tooltip>
      ),
      editable: false,
    },
    {
      title: "设备状态",
      dataIndex: "nvr_state",

      render: (val) => {
        switch (val) {
          case 1:
            return "在线";
          case 0:
            return "离线";
          default:
            break;
        }
      },
      editable: false,
    },
    {
      title: "优惠开启时间",
      dataIndex: "discount_start_time",
      width: 168,
      render: (val, record) => {
        const editable = isEditing(record);
        return (
          <Space direction="vertical">
            <DatePicker
              defaultValue={moment(
                val ? `${val} 00:00:00` : "2022-01-01 00:00:00",
                "YYYY-MM-DD HH:mm:ss"
              )}
              disabledDate={(current) =>
                current && current < moment().endOf("day")
              }
              showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
              onChange={startTimeChange}
              disabled={!editable}
            />
          </Space>
        );
      },
      editable: false,
    },
    {
      title: "优惠结束时间",
      dataIndex: "discount_end_time",
      width: 168,
      render: (val, record) => {
        const editable = isEditing(record);
        return (
          <Space direction="vertical">
            <DatePicker
              className={new Date(val) < new Date() ? "outmod" : "nooutmod"}
              defaultValue={moment(
                val ? `${val} 23:59:59` : "2022-01-01 23:59:59",
                "YYYY-MM-DD HH:mm:ss"
              )}
              disabledDate={(current) =>
                current &&
                current < moment(record.discount_start_time).endOf("day")
              }
              showTime={{ defaultValue: moment("23:59:59", "HH:mm:ss") }}
              onChange={endTimeChange}
              disabled={!editable}
            />
          </Space>
        );
      },
      editable: false,
    },
    {
      title: "原价(元/天)",
      dataIndex: "initial_prices",
      editable: false,
      width: 100,
      render: (val, record) => {
        const editable = isEditing(record);
        function onChange(numberVal) {
          setSelectedData({ ...selectedData, initial_prices: numberVal });
        }
        return editable ? (
          <InputNumber
            defaultValue={val}
            style={{ width: 89 }}
            min={0.01}
            max={max}
            formatter={(value) =>
              `￥${Number(value.toString().match(/^\d+(?:\.\d{0,2})?/))}`
            }
            onChange={onChange}
          />
        ) : (
          val
        );
      },
    },
    {
      title: "优惠(元/天)",
      dataIndex: "discount",
      width: 100,
      render: (val, record) => {
        const editable = isEditing(record);
        function onChange(numberVal) {
          setSelectedData({ ...selectedData, discount: numberVal });
        }
        return editable ? (
          <InputNumber
            defaultValue={val}
            style={{ width: 89 }}
            min={0}
            onChange={onChange}
            formatter={(value) =>
              `￥${Number(value.toString().match(/^\d+(?:\.\d{0,2})?/))}`
            }
            max={max}
          />
        ) : (
          val
        );
      },
      editable: false,
    },
    {
      title: "实价(元/天)",
      render: (_, obj) => {
        return new Date(obj.discount_end_time) > new Date()
          ? (obj.initial_prices * 1e3 - obj.discount * 1e3) / 1e3
          : obj.initial_prices;
      },
      editable: false,
    },
    {
      title: "折扣",
      render: (_, obj) => {
        return (
          (
            ((obj.initial_prices * 1e3 - obj.discount * 1e3) /
              (obj.initial_prices * 1e3)) *
            10
          ).toFixed(2) + " 折"
        );
      },
      editable: false,
    },
    {
      title: "产品属性",
      dataIndex: "sales_status",
      width: 110,
      render: (val, record) => {
        const editable = isEditing(record);
        function onSelect(select) {
          setSelectedData({ ...selectedData, sales_status: select });
        }
        return (
          <Select
            defaultValue={val && String(val)}
            style={{ width: 90 }}
            disabled={!editable}
            onSelect={onSelect}
          >
            <Option value="1">已售</Option>
            <Option value="2">已租</Option>
            <Option value="3">测试机</Option>
          </Select>
        );
      },
      editable: false,
    },
    {
      title: "隶属",
      dataIndex: "nvr_ownership",
      render: (val, record) => {
        const editable = isEditing(record);
        const onBlur = (e) => {
          setSelectedData({ ...selectedData, nvr_ownership: e.target.value });
        };
        return editable ? (
          <Input defaultValue={val} maxLength={15} onBlur={onBlur} />
        ) : (
          <Tooltip placement="top" title={val}>
            <span>{val}</span>
          </Tooltip>
        );
      },
      width: 120,
      editable: false,
      ellipsis: true,
    },
    {
      title: "操作",
      width: "235px",
      fixed: "right",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);

        return (
          <>
            <Button size="small" type="primary" onClick={() => qrcode(record)}>
              付款码
            </Button>
            &nbsp;
            <Button
              size="small"
              type="primary"
              onClick={() => toRouter(record.nvr_IMEI)}
            >
              订单
            </Button>{" "}
            &nbsp;
            {editable ? (
              <>
                <Button
                  size="small"
                  type="primary"
                  onClick={() => save()}
                  style={{
                    lineHeight: 1.4,
                    padding: "0 2px",
                    marginRight: 8,
                  }}
                >
                  保存
                </Button>
                <Popconfirm title="确定取消?" onConfirm={cancel}>
                  <a>取消</a>
                </Popconfirm>
              </>
            ) : (
              <Button
                style={{
                  display: localStorage.getItem("role") == 2 ? "none" : "",
                }}
                size="small"
                type="primary"
                disabled={editingKey !== ""}
                onClick={() => editChange(record)}
              >
                编辑
              </Button>
            )}
          </>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <>
      <Modal
        title={
          <div
            style={{
              width: "100%",
              cursor: "move",
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            验证密码
          </div>
        }
        centered
        confirmLoading={loading}
        visible={visible}
        onOk={verifyPassword}
        onCancel={() => setVisible(false)}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
        width={380}
      >
        <p>您正在修改设备参数, 请输入密码进行身份验证！</p>
        输入密码：
        <Input.Password
          type="password"
          style={{ width: 200 }}
          onChange={(e) => {
            setPassword(e.target.value);
          }}
        />
      </Modal>

      <Modal
        title={
          <div
            style={{
              width: "100%",
              cursor: "move",
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            二维码
          </div>
        }
        centered
        visible={Qrvisible}
        onCancel={() => setQrvisible(false)}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
        width={300}
        footer={
          <Button type="primary" onClick={() => setQrvisible(false)}>
            关闭
          </Button>
        }
      >
        <QRCode
          value={`http://pay.sanhevideo.com.cn:9999/?nvr_IMEI=${selectedData.nvr_IMEI}`} // value参数为生成二维码的链接
          size={252} // 二维码的宽高尺寸
          fgColor="#0f0f0f" // 二维码的颜色
          style={{ margin: "0 auto" }}
        />
        <h2 style={{ padding: "20px 10px 0", margin: 0, textAlign: "center" }}>
          设备ID：{selectedData.nvr_IMEI}
        </h2>
      </Modal>

      <Form form={form} component={false} className="TableDom">
        <Table
          size="small"
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          scroll={{ x: 1300 }}
          bordered
          rowKey={(record) => record.nvr_IMEI}
          dataSource={eqDatas.data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: pageChange,
            position: ["bottomCenter"],
            defaultPageSize: defaultLimit,
            total: eqDatas.count, //总条数
          }}
        />
      </Form>
    </>
  );
};

const Equipent = () => {
  return (
    <>
      <Serch />
    </>
  );
};

export default Equipent;
